// Innitial map values
var map;
var directionsService;
var markers = [];

window.onload = function() {
	initialize();
}

function initialize() {
	// Set initial center position
	var latlng = new google.maps.LatLng(50.979865,4.081088);
	
	var myOptions = {
		zoom:15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	directionsService = new google.maps.DirectionsService();
	
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	// Add marker on click
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng, true);
	});

}

function addMarker(position, snap) {
	if(snap) {
		var request = {
			origin: position,
			destination: position,
			travelMode: google.maps.DirectionsTravelMode.WALKING
		};
		
		var icon = new google.maps.MarkerImage(
			'http://localhost/gmfb/core/img/mapIcons/icon32.png',
			new google.maps.Size(32,32),
			new google.maps.Point(0,0),
			new google.maps.Point(16,32)
			);
		
		// Snap marker to road by calculating route to self
		directionsService.route(request, function(response, status) {
			var marker = new google.maps.Marker({
				position: response.routes[0].legs[0].start_location, 
				map: map,
				icon: icon,
				draggable: true
			});
			// Add marker to array
			markers.push(marker);
			
			if(markers.length > 1) {
				calcRoute();
			}
		});
	}
}

function calcRoute() {
	var origin = markers[markers.length - 2];
	var destination = markers[markers.length - 1];
	drawRoute(origin.getPosition(), destination.getPosition());
}

function drawRoute(origin, destination) {
	var markerOptions = {
		suppressMarkers: true
	};
	
	var directionsOptions = {
		preserveViewport: true,
		markerOptions: markerOptions
	};
	
	var directionsDisplay = new google.maps.DirectionsRenderer(directionsOptions);
	directionsDisplay.suppressMarkers = true;
	directionsDisplay.setMap(map);
	
	request = {
		origin: origin,
		destination: destination,
		travelMode: google.maps.DirectionsTravelMode.WALKING
	};
	
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
}